<template>
  <div>
    <el-form
      :model="userInfo"
      :rules="rules"
      ref="userForm"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-form-item label="用户名">
        <el-input v-model="userInfo.userName" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input v-model="userInfo.userEmail"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="userMobile">
        <el-input v-model="userInfo.userMobile"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submitForm">修改</el-button>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  data() {
    return {
      userInfo: {
        userName: '',
        userEmail: '',
        userMobile: ''
      },
      rules: {
        userEmail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ],
        userMobile: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  computed: {
    ...mapState(['user'])
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    // 个人信息
    getUserInfo() {
      this.$axios
        .get(`http://localhost:8091/account/${this.user.id}`)
        .then((res) => {
          let code = res.data.code;
          if (code === 200) {
            this.userInfo = res.data.data;
          } else {
            this.$message.error(res.data.message || '获取用户信息失败');
          }
        })
        .catch((err) => {
          console.error(err);
          this.$message.error('获取用户信息失败');
        });
    },
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.updateUserInfo();
        } else {
          this.$message.error('请检查输入信息');
          return false;
        }
      });
    },
    // 修改个人信息
    updateUserInfo() {
      this.$axios
        .put(`http://localhost:8091/account/${this.user.id}`, this.userInfo)
        .then((response) => {
          this.$message.success('信息修改成功');
        })
        .catch((error) => {
          console.error(error);
          this.$message.error('修改失败');
        });
    }
  }
};
</script>

<style scoped>
</style>